package com.inspection.service.impl;

import com.google.common.collect.Lists;
import com.inspection.dao.InspectionBasicDao;
import com.inspection.entity.InspectionBasicDO;
import com.inspection.entity.SysUserDO;
import com.inspection.model.dto.InspectionBasicDTO;
import com.inspection.model.dto.InspectionBasicQueryDTO;
import com.inspection.service.InspectionBasicService;
import com.inspection.support.AssertUtils;
import com.inspection.support.PageHelper;
import com.inspection.support.SortHelper;
import com.inspection.support.model.BusinessBaseException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.persistence.Id;
import javax.persistence.criteria.Predicate;
import java.util.*;

/**
 * @author : chenjx
 * create at:  2020/11/8  7:44 下午
 */
@Service("InspectionBasicService")
public class InspectionBasicServiceImpl implements InspectionBasicService {

    @Autowired
    private InspectionBasicDao inspectionBasicDao;
    //可选考核类别
    @Override
    public List<String> queryUsableRegulationType() {
        Sort sort = new Sort(Sort.Direction.DESC,"id");
        InspectionBasicDO basicParam = new InspectionBasicDO();
        basicParam.setIsDel(0);
        List<InspectionBasicDO> basicDOList = inspectionBasicDao.findAll(Example.of(basicParam),sort);
        Set<String> typeSet = new HashSet<>(basicDOList.size());
        basicDOList.forEach(b-> typeSet.add(b.getInspectionType()));
        return new ArrayList<>(typeSet);
    }
    @Override
    public List<InspectionBasicDO> getInspectionBasicList(InspectionBasicDO query) {
        return inspectionBasicDao.findAll(Example.of(query));
    }

    @Override
    public Page<InspectionBasicDO> pageInspectionBasic(InspectionBasicQueryDTO page) {
        Sort sort = SortHelper.buildSort(page);
        PageHelper check = PageHelper.check(page.getPageNo(), page.getPageSize());
        Pageable pageable = PageRequest.of(check.getOffset(), check.getPageSize(), sort);

        return inspectionBasicDao.findAll((Specification<InspectionBasicDO>) (root, criteriaQuery, criteriaBuilder) -> {

            List<Predicate> predicates = Lists.newArrayList();
            predicates.add(criteriaBuilder.equal(root.get("isDel"),0));

            if (!StringUtils.isEmpty(page.getInspectionType())) {
                predicates.add(criteriaBuilder.like(root.get("inspectionType"), "%"+page.getInspectionType()+"%"));
            }

            if (!StringUtils.isEmpty(page.getInspectionCycle())) {
                predicates.add(criteriaBuilder.equal(root.get("inspectionCycle"), page.getInspectionCycle()));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        }, pageable);
    }

    @Override
    public void addInspectionBasic(InspectionBasicDO basicDO) {

        //同一个考核类别+考核  只能存在一条

        InspectionBasicDO basicQuery = new InspectionBasicDO();
        basicQuery.setIsDel(0);
        basicQuery.setInspectionType(basicDO.getInspectionType());
        basicQuery.setInspectionCycle(basicDO.getInspectionCycle());

        List<InspectionBasicDO> existBasics = inspectionBasicDao.findAll(Example.of(basicQuery));
        if (!CollectionUtils.isEmpty(existBasics)) {
            throw new BusinessBaseException("已存在相同类别+考核周期的考核基础");
        }


        basicDO.setIsDel(0);
        basicDO.setDateCreate(new Date());
        inspectionBasicDao.save(basicDO);
    }

    @Override
    public void updateInspectionBasic(InspectionBasicDO basicDO) {
        AssertUtils.nonNull(basicDO.getId(),"id不能为空！");

        InspectionBasicDO basicQuery = new InspectionBasicDO();
        basicQuery.setId(basicDO.getId());
        Optional<InspectionBasicDO> basicOp = inspectionBasicDao.findOne(Example.of(basicQuery));
        if(!basicOp.isPresent()){
            throw new BusinessBaseException("考核基础不存在！");
        }


        //存在考核类型和周期修改的情况下 如果还是原来的，可以不用处理=
        //同一个考核类别+考核  只能存在一条
        if (!basicDO.getInspectionType().equals(basicOp.get().getInspectionType())
                || !basicDO.getInspectionCycle().equals(basicOp.get().getInspectionCycle())) {
            InspectionBasicDO sameBasicQuery = new InspectionBasicDO();
            sameBasicQuery.setIsDel(0);
            sameBasicQuery.setInspectionType(basicDO.getInspectionType());
            sameBasicQuery.setInspectionCycle(basicDO.getInspectionCycle());

            List<InspectionBasicDO> existBasics = inspectionBasicDao.findAll(Example.of(sameBasicQuery));
            if (!CollectionUtils.isEmpty(existBasics)) {
                throw new BusinessBaseException("已存在相同类别+考核周期的考核基础");
            }
        }



        InspectionBasicDO basicUpdate = basicOp.get();
        basicUpdate.setInspectionType(basicDO.getInspectionType());
        basicUpdate.setInspectionCycle(basicDO.getInspectionCycle());
        basicUpdate.setInspectionCycleTotalScore(basicDO.getInspectionCycleTotalScore());
        inspectionBasicDao.saveAndFlush(basicUpdate);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delInspectionBasic(InspectionBasicDO basicDO) {
        AssertUtils.nonNull(basicDO.getId(),"id不能为空！");

        InspectionBasicDO basicParam = new InspectionBasicDO();
        basicParam.setId(basicDO.getId());
        Optional<InspectionBasicDO> basicOp = inspectionBasicDao.findOne(Example.of(basicParam));
        if(!basicOp.isPresent()){
            throw new BusinessBaseException("考核基础不存在！");
        }
        InspectionBasicDO basicUpdate = basicOp.get();
        basicUpdate.setIsDel(1);
        inspectionBasicDao.saveAndFlush(basicUpdate);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelInspectionBasic(InspectionBasicDTO del) {
        AssertUtils.notEmpty(del.getIdList(),"idList不能为空！");

        List<InspectionBasicDO> basics = inspectionBasicDao.findAllById(del.getIdList());
        if(CollectionUtils.isEmpty(basics)){
            throw new BusinessBaseException("考核基础不存在！");
        }
        for (InspectionBasicDO basic : basics) {
            basic.setIsDel(1);
            inspectionBasicDao.saveAndFlush(basic);
        }
    }

    @Override
    public InspectionBasicDO getInspectionBasic(InspectionBasicQueryDTO basicQuery) {
        AssertUtils.nonNull(basicQuery.getId(),"id不能为空！");

        InspectionBasicDO basicParam = new InspectionBasicDO();
        basicParam.setId(basicQuery.getId());
        Optional<InspectionBasicDO> basicOp = inspectionBasicDao.findOne(Example.of(basicParam));
        if(!basicOp.isPresent()){
           throw new BusinessBaseException("考核基础不存在！");
        }
        return basicOp.get();
    }
}
